import Vue from "vue";
import Router from "vue-router";
import Home from "../views/Home.vue";
import store from "../store";

const routerPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error => error);
};
Vue.use(Router);
const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
    meta: {
      public: true
    }
  },
  {
    path: "/detail",
    name: "detail",
    component: () => import(/* webpackChunkName: "about" */ "../views/detail.vue")
  },
  {
    path: "/cart",
    name: "cart",
    component: () => import(/* webpackChunkName: "about" */ "../views/cart.vue")
  },
  {
    path: "/order",
    name: "order",
    component: () => import(/* webpackChunkName: "about" */ "../views/order.vue")
  },
  {
    path: "/myorder",
    name: "myorder",
    component: () => import(/* webpackChunkName: "about" */ "../views/myorder.vue")
  },
  {
    path: "/pinlun",
    name: "pinlun",
    component: () => import(/* webpackChunkName: "about" */ "../views/pinlun.vue")
  },
  {
    path: "/profile",
    name: "profile",
    component: () => import(/* webpackChunkName: "about" */ "../views/profile.vue")
  },
  {
    path: "/list",
    name: "list",
    component: () => import(/* webpackChunkName: "about" */ "../views/list.vue")
  },
  {
    path: "/login",
    name: "login",
    meta: {
      public: true
    },
    component: () => import(/* webpackChunkName: "about" */ "../views/login.vue")
  },
  {
    path: "/register",
    name: "register",
    meta: {
      public: true
    },
    component: () => import(/* webpackChunkName: "about" */ "../views/register.vue")
  },
  {
    path: "/password",
    name: "password",
    meta: {
      public: true
    },
    component: () => import(/* webpackChunkName: "about" */ "../views/password.vue")
  }
];

const behavior = (to, from, save) => {
  return { x: 0, y: 0 };
};
const router = new Router({
  routes,
  scrollBehavior: behavior
});

router.beforeEach((to, from, next) => {
  if (store.state.isLogin) {
    next();
  } else {
    const token = localStorage.getItem("token");
    if (token) {
      store.dispatch("getUserInfo");
      next();
    } else {
      if (to.meta.public) {
        next();
      } else {
        next("/login");
      }
    }
  }
});
export default router;
